<?php

class User extends Model
{
    const table_name = 'user';

    public static $UserCookieName = 'USER';
    public static $UserLoginExpire = 1200;

    public static $f_user = 'uid, unid, username, add_time';
    public static $f_user_detail = 'uid, unid, username';
    public static $f_user_verify = 'uid, unid, username, password';

    /**
     * 验证登录信息
     * @param string $username
     * @param string $password
     *
     * @return array
     */
    public static function verifyUserLogin($username, $password)
    {
        $user = self::getOneByFields([['username', $username]], self::$f_user_verify);

        if (!empty($user)) {
            $bool = password_verify($password, $user['password']);
            if ($bool) {
                return array(
                    'username' => $user['username'],
                    'uid' => $user['uid'],
                    'unid' => $user['unid'],
                );
            } else {
                return array();
            }
        } else {
            return array();
        }

    }

    /**
     * desc 根据手机号获取uid
     * @param $mobile
     * @param $field
     * @return string
     */
    public static function getUserInfoByMobile($mobile)
    {
        return self::getOneByFields( [['mobile', $mobile]], self::$f_user);
    }
    
    /**
     * desc 根据用户id获取用户信息
     * @param $uid
     * @param string $field
     * @return array|mixed
     */
    public static function getUserInfoById($uid, $field='')
    {
        $rs = self::getOneByFields([['uid', $uid]], self::$f_user);
        
        return (!empty($field) && !empty($rs[$field])) ? $rs[$field] : $rs;
    }

    /**
     * desc 记录用户登录信息
     * @param $user
     * @param int $expire 有效期(秒)
     */
    public static function setUserCookie($user, $expire=0)
    {
        $user['login_time'] = REQUEST_TIME; //当前时间
        $user['expire'] = $expire; //有效期
        $expired = time()+$expire;
        $user['expired_time'] = date('Y-m-d H:i:s', $expired); //到期时间
        $json = json_encode($user);
        $secret = Fun::openssl($json);
        $arr = explode('.', $_SERVER['SERVER_NAME']);
        $domain = $arr[count($arr)-2].'.'.$arr[count($arr)-1]; //全域名有效
        
        if (empty($expire)) {
            setcookie(self::$UserCookieName, $secret, 0, '/', $domain, FALSE, TRUE); //关闭浏览器即失效
        } else {
            setcookie(self::$UserCookieName, $secret, $expired, '/', $domain, FALSE, TRUE);
        }
        
    }

    /**
     * desc 获取用户信息
     * @param string $filed
     * @return string|array
     */
    public static function getUserCookie($filed='')
    {
        if (!empty(Request::Cookie(self::$UserCookieName))) {
            $secret = Request::Cookie(self::$UserCookieName);
            $json = Fun::openssl($secret, FALSE);
            $user = json_decode($json, TRUE);

            if (empty($user['expire'])) {
                if (REQUEST_TIME - $user['login_time'] > self::$UserLoginExpire) {
                    return [];
                }
            } else {
                if (strcmp(REQUEST_DATETIME, $user['expired_time']) > 0) {
                    return [];
                }
            }

            if (!empty($filed) && !empty($user[$filed])) {
                return $user[$filed];
            } else {
                return $user;
            }
        } else {
            return [];
        }

    }

    /**
     * desc 清空用户登录信息
     */
    public static function clearUserCookie()
    {
        $arr = explode('.', $_SERVER['SERVER_NAME']);
        $domain = $arr[count($arr)-2].'.'.$arr[count($arr)-1]; //全域名有效
        setcookie(self::$UserCookieName, '-1', time()-3600, '/', $domain,FALSE, TRUE);
    }

    //加密密码
    public static function makePassword($password)
    {
        return password_hash($password, PASSWORD_BCRYPT);
    }

    //更新密码
    public static function changePassword($uid, $password)
    {
        $password = User::makePassword($password);
        return self::saveByUnid(['password' => $password], $uid);
    }

    public static function afterRegister($unid)
    {
        $id = DBQueue::push(TopicConfig::topic_user_register, ['user_code' => $unid], $unid);
        FileLog::info("用户注册成功, 插入消息表. $unid, $id", 'user');
    }

    public static function afterLogin($unid)
    {
        $id = DBQueue::push(TopicConfig::topic_user_login, ['user_code' => $unid], $unid);
    }

}